<template>
    <div class="friend-links">
      <!-- <h1>友链管理</h1> -->
      <div class="form-group">
        <label>站点名称</label>
        <input v-model="newLinkName" type="text" placeholder="站点名称" />
        <label>站点 URL</label>
        <input v-model="newLinkUrl" type="text" placeholder="站点 URL" />
        <button @click="addLink">添加友链</button>
      </div>
      <ul>
        <li v-for="link in friendLinks" :key="link.id">
          {{ link.site_name }} - <a :href="link.site_url" target="_blank">{{ link.site_url }}</a>
          <button @click="deleteLink(link.id)">删除</button>
        </li>
      </ul>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import axios from 'axios';
  
  interface FriendLink {
    id: string | number; // 根据实际情况调整类型
    site_name: string;
    site_url: string;
}

  const userId = '1'; // 替换为实际用户 ID
  const newLinkName = ref('');
  const newLinkUrl = ref('');
  const friendLinks = ref<FriendLink[]>([]);
  
  const fetchFriendLinks = async () => {
    const response = await axios.get(`http://localhost:5000/api/user/${userId}/sitesr`);
    if (response.data.code === 200) {
      friendLinks.value = response.data.data;
    }
  };
  
  const addLink = async () => {
    const response = await axios.post(`http://localhost:5000/api/user/${userId}/sites`, {
      site_name: newLinkName.value,
      site_url: newLinkUrl.value,
    });
    if (response.data.code === 200) {
      alert('友链添加成功！');
      fetchFriendLinks(); // 刷新友链列表
      newLinkName.value = '';
      newLinkUrl.value = '';
    } else {
      alert('添加失败，请重试！');
    }
  };
  
  const deleteLink = async (linkId: string | number) => {
    const response = await axios.delete(`http://localhost:5000/api/user/${userId}/sites/${linkId}`);
    if (response.data.code === 200) {
      alert('友链删除成功！');
      fetchFriendLinks(); // 刷新友链列表
    } else {
      alert('删除失败，请重试！');
    }
  };
  
  onMounted(() => {
    fetchFriendLinks(); // 获取友链列表
  });
  </script>
  
  <style scoped>
  .friend-links {
    /* 添加样式 */
  }
  </style>